<template>
  <div class="version-selector">
    <el-select
      v-model="selectedValue"
      :placeholder="placeholder"
      :multiple="multiple"
      :filterable="filterable"
      :clearable="clearable"
      :disabled="disabled"
      :loading="loading"
      :size="size"
      :style="{ width: width }"
      @change="handleChange"
      @clear="handleClear"
      @focus="handleFocus"
    >
      <template #prefix v-if="showIcon">
        <el-icon><FolderOpened /></el-icon>
      </template>
      
      <template v-if="groupBy">
        <el-option-group
          v-for="group in groupedVersions.filter(g => g.options.length > 0)"
          :key="group.label"
          :label="group.label"
        >
        <el-option
          v-for="version in group.options"
          :key="version.id"
          :label="getVersionLabel(version)"
          :value="version.id"
          :disabled="isVersionDisabled(version)"
        >
          <div class="version-option">
            <div class="version-info">
              <div class="version-header">
                <span class="version-number">{{ version.version_number }}</span>
                <VersionStatusTag 
                  :status="version.status" 
                  size="small" 
                  :show-icon="false"
                />
              </div>
              <div class="version-name">{{ version.name }}</div>
              <div class="version-meta" v-if="showMeta">
                <span class="project-name">{{ version.project_name }}</span>
                <span class="release-date" v-if="version.planned_release_date">
                  {{ formatDate(version.planned_release_date) }}
                </span>
              </div>
            </div>
            <div class="version-actions" v-if="showActions">
              <el-tooltip content="查看详情" placement="top">
                <el-button 
                  type="text" 
                  size="small" 
                  @click.stop="viewDetail(version)"
                >
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </el-option>
        </el-option-group>
      </template>
      
      <el-option
        v-for="version in filteredVersions"
        :key="version.id"
        :label="getVersionLabel(version)"
        :value="version.id"
        :disabled="isVersionDisabled(version)"
        v-if="!groupBy"
      >
        <div class="version-option">
          <div class="version-info">
            <div class="version-header">
              <span class="version-number">{{ version.version_number }}</span>
              <VersionStatusTag 
                :status="version.status" 
                size="small" 
                :show-icon="false"
              />
            </div>
            <div class="version-name">{{ version.name }}</div>
            <div class="version-meta" v-if="showMeta">
              <span class="project-name">{{ version.project_name }}</span>
              <span class="release-date" v-if="version.planned_release_date">
                {{ formatDate(version.planned_release_date) }}
              </span>
            </div>
          </div>
          <div class="version-actions" v-if="showActions">
            <el-tooltip content="查看详情" placement="top">
              <el-button 
                type="text" 
                size="small" 
                @click.stop="viewDetail(version)"
              >
                <el-icon><View /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </el-option>
      
      <template #empty>
        <div class="empty-content">
          <el-icon><FolderOpened /></el-icon>
          <p>{{ emptyText }}</p>
        </div>
      </template>
    </el-select>
    
    <!-- 已选择版本展示 -->
    <div class="selected-versions" v-if="multiple && selectedVersions.length > 0 && showSelected">
      <div class="selected-header">
        <span>已选择 {{ selectedVersions.length }} 个版本</span>
        <el-button type="text" size="small" @click="clearAll">清空</el-button>
      </div>
      <div class="selected-list">
        <el-tag
          v-for="version in selectedVersions"
          :key="version.id"
          closable
          @close="removeVersion(version.id)"
          class="selected-tag"
        >
          {{ version.version_number }} - {{ version.name }}
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElIcon } from 'element-plus'
import {
  FolderOpened,
  View
} from '@element-plus/icons-vue'
import { versionAPI, type Version } from '@/api/version'
import { formatDate } from '@/utils/date'
import VersionStatusTag from './VersionStatusTag.vue'
import { useVersionStates } from '@/composables/useVersionStates'

interface Props {
  modelValue?: string | string[]
  placeholder?: string
  multiple?: boolean
  filterable?: boolean
  clearable?: boolean
  disabled?: boolean
  size?: 'large' | 'default' | 'small'
  width?: string
  showIcon?: boolean
  showMeta?: boolean
  showActions?: boolean
  showSelected?: boolean
  emptyText?: string
  // 筛选条件
  projectId?: string
  status?: string | string[]
  excludeIds?: string[]
  // 分组选项
  groupBy?: 'project' | 'status' | 'release_date'
  // 自定义验证
  validator?: (version: Version) => boolean
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '请选择版本',
  multiple: false,
  filterable: true,
  clearable: true,
  disabled: false,
  size: 'default',
  width: '100%',
  showIcon: true,
  showMeta: true,
  showActions: false,
  showSelected: true,
  emptyText: '暂无可选版本'
})

const emit = defineEmits<{
  'update:modelValue': [value: string | string[]]
  'change': [value: string | string[], versions: Version | Version[]]
  'clear': []
  'focus': []
  'view-detail': [version: Version]
}>()

const router = useRouter()

// 响应式数据
const loading = ref(false)
const versions = ref<Version[]>([])
const selectedValue = ref<string | string[]>(props.multiple ? [] : '')

// 计算属性
const filteredVersions = computed(() => {
  let result = versions.value

  // 项目筛选
  if (props.projectId) {
    result = result.filter(v => v.project_id === props.projectId)
  }

  // 状态筛选
  if (props.status) {
    const statusArray = Array.isArray(props.status) ? props.status : [props.status]
    result = result.filter(v => statusArray.includes(v.status))
  }

  // 排除指定版本
  if (props.excludeIds?.length) {
    result = result.filter(v => !props.excludeIds!.includes(v.id))
  }

  // 自定义验证
  if (props.validator) {
    result = result.filter(props.validator)
  }

  return result
})

const groupedVersions = computed(() => {
  if (!props.groupBy) return []

  const groups: { label: string; options: Version[] }[] = []
  const groupMap = new Map<string, Version[]>()

  filteredVersions.value.forEach(version => {
    let groupKey = ''

    switch (props.groupBy) {
      case 'project':
        groupKey = version.project_id
        break
      case 'status':
        groupKey = version.status
        break
      case 'release_date':
        const date = version.planned_release_date
        if (date) {
          const month = new Date(date).toISOString().slice(0, 7)
          groupKey = month
        } else {
          groupKey = 'no-date'
        }
        break
    }

    if (!groupMap.has(groupKey)) {
      groupMap.set(groupKey, [])
    }
    groupMap.get(groupKey)!.push(version)
  })

  groupMap.forEach((options, key) => {
    const label = key === 'no-date' ? '未设置发布日期' : 
                  props.groupBy === 'project' ? options[0]?.project_name || '未知项目' :
                  props.groupBy === 'status' ? getStatusText(key) :
                  `${key} 计划发布`
    
    groups.push({ label, options })
  })

  return groups.sort((a, b) => a.label.localeCompare(b.label))
})

const selectedVersions = computed(() => {
  if (!props.multiple) return []
  const ids = Array.isArray(selectedValue.value) ? selectedValue.value : []
  return versions.value.filter(v => ids.includes(v.id))
})

// 监听器
watch(() => props.modelValue, (newValue) => {
  selectedValue.value = newValue || (props.multiple ? [] : '')
}, { immediate: true })

watch(() => [props.projectId, props.status, props.excludeIds], () => {
  fetchVersions()
}, { deep: true })

// 方法
const fetchVersions = async () => {
  try {
    loading.value = true
    const params: any = {
      limit: 100,
      skip: 0
    }

    if (props.projectId) {
      params.project_id = props.projectId
    }

    const response = await versionAPI.getVersions(params)
    versions.value = response?.data?.items || []
  } catch (error) {
    console.error('获取版本列表失败:', error)
    ElMessage.error('获取版本列表失败')
  } finally {
    loading.value = false
  }
}

const getVersionLabel = (version: Version) => {
  return `${version.version_number} - ${version.name}`
}

const isVersionDisabled = (version: Version) => {
  if (props.disabled) return true
  if (props.validator && !props.validator(version)) return true
  return false
}

// 从状态管理系统动态获取状态信息
const { getStateName } = useVersionStates()

const getStatusText = (status: string) => {
  return getStateName(status) || status
}

// 事件处理
const handleChange = (value: string | string[]) => {
  emit('update:modelValue', value)
  
  if (props.multiple) {
    const ids = Array.isArray(value) ? value : []
    const selectedVersionList = versions.value.filter(v => ids.includes(v.id))
    emit('change', value, selectedVersionList)
  } else {
    const selectedVersion = versions.value.find(v => v.id === value)
    emit('change', value, selectedVersion!)
  }
}

const handleClear = () => {
  emit('clear')
}

const handleFocus = () => {
  emit('focus')
  // 移除focus时的自动获取，避免重复调用
  // 版本数据应该在组件初始化时或属性变化时获取
}

const viewDetail = (version: Version) => {
  emit('view-detail', version)
  router.push(`/versions/${version.id}`)
}

const removeVersion = (versionId: string) => {
  if (Array.isArray(selectedValue.value)) {
    const newValue = selectedValue.value.filter(id => id !== versionId)
    selectedValue.value = newValue
    handleChange(newValue)
  }
}

const clearAll = () => {
  selectedValue.value = []
  handleChange([])
}

// 生命周期
onMounted(() => {
  fetchVersions()
})

// 暴露方法
defineExpose({
  fetchVersions,
  clearSelection: clearAll
})
</script>

<style scoped>
.version-selector {
  width: 100%;
}

.version-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  width: 100%;
}

.version-info {
  flex: 1;
  min-width: 0;
}

.version-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.version-number {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

.version-name {
  font-size: 13px;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.version-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.project-name {
  font-weight: 500;
}

.version-actions {
  flex-shrink: 0;
  margin-left: 8px;
}

.empty-content {
  text-align: center;
  padding: 20px;
  color: #909399;
  
  .el-icon {
    font-size: 24px;
    margin-bottom: 8px;
  }
  
  p {
    margin: 0;
    font-size: 14px;
  }
}

.selected-versions {
  margin-top: 12px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;
}

.selected-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 13px;
  color: #606266;
}

.selected-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-tag {
  max-width: 200px;
  
  :deep(.el-tag__content) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .version-option {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .version-actions {
    margin-left: 0;
    align-self: flex-end;
  }
  
  .version-meta {
    flex-direction: column;
    gap: 4px;
  }
  
  .selected-list {
    flex-direction: column;
  }
  
  .selected-tag {
    max-width: 100%;
  }
}
</style>